<template>
  <div class="goods-image">
    <div class="middle" ref="target">
      <!-- 主图 -->
      <img :src="images[currentIndex]" alt="" />
      <!-- 遮罩层 -->
      <div :style="layerPosition" v-show="!isOutside" class="layer"></div>
    </div>
    <!-- 小图列表 -->
    <ul class="small">
      <li v-for="(item, index) in images" :key="index">
        <img :src="item" alt="" @mouseenter="currentIndex = index" />
      </li>
    </ul>
    <!-- 右侧预览大图 -->
    <div v-show="!isOutside" class="large">
      <img :style="largePosition" :src="images[currentIndex]" alt="">
    </div>
  </div>
</template>

<script>
import { ref, watch, reactive } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    // 右侧小图列表当前显示索引值
    const currentIndex = ref(0)

    const target = ref(null)
    const { isOutside, elementX, elementY } = useMouseInElement(target)

    // 遮罩层坐标
    const layerPosition = reactive({ top: 0, left: 0 })
    // 预览大图坐标
    const largePosition = reactive({ top: 0, left: 0 })

    // 监听X和Y坐标
    watch([elementX, elementY], () => {
      let top = elementY.value - 100
      let left = elementX.value - 100

      // 遮罩层边界
      if (top < 0) top = 0
      if (left < 0) left = 0
      if (top > 200) top = 200
      if (left > 200) left = 200

      // 重新赋值坐标
      // 遮罩层
      layerPosition.top = top + 'px'
      layerPosition.left = left + 'px'
      // 预览
      largePosition.top = -1 * 2 * top + 'px'
      largePosition.left = -1 * 2 * left + 'px'
    })

    return { currentIndex, isOutside, target, layerPosition, largePosition }
  }
}
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f5f5f5;
    overflow: hidden;
    z-index: 500;
    img {
      max-width: 800px;
      min-width: 800px;
      max-height: 800px;
      min-height: 800px;
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
